#!/usr/bin/env python3
"""
深入分析二进制数据结构，寻找加密算法
"""

import struct
import math
from collections import Counter
import json

def load_data():
    """加载所有相关数据"""
    with open('encript_body.txt', 'r') as f:
        encrypted = f.read().strip()
    
    with open('decoded_result.bin', 'rb') as f:
        decoded = f.read()
    
    return encrypted, decoded

def analyze_byte_patterns(data):
    """分析字节模式"""
    print("📊 === 字节模式分析 ===\n")
    
    # 1. 字节分布熵
    byte_counts = Counter(data)
    total = len(data)
    entropy = -sum((count/total) * math.log2(count/total) for count in byte_counts.values())
    print(f"数据熵: {entropy:.4f} (随机数据约8.0)")
    
    # 2. 连续相同字节
    max_run = 0
    current_run = 1
    prev_byte = data[0]
    
    for byte in data[1:]:
        if byte == prev_byte:
            current_run += 1
            max_run = max(max_run, current_run)
        else:
            current_run = 1
        prev_byte = byte
    
    print(f"最长连续相同字节: {max_run}")
    
    # 3. 字节差异分析
    differences = []
    for i in range(1, min(1000, len(data))):
        diff = (data[i] - data[i-1]) % 256
        differences.append(diff)
    
    diff_counter = Counter(differences)
    print(f"\n字节差异分布 (前1000字节):")
    for diff, count in diff_counter.most_common(5):
        print(f"  差值 {diff}: {count}次")
    
    return byte_counts

def analyze_block_structure(data, block_sizes=[8, 16, 32, 64]):
    """分析块结构"""
    print("\n\n🔲 === 块结构分析 ===")
    
    for block_size in block_sizes:
        print(f"\n{block_size}字节块分析:")
        
        # 分割成块
        blocks = [data[i:i+block_size] for i in range(0, len(data)-block_size, block_size)]
        
        # 统计重复块
        block_counter = Counter(blocks)
        repeated = sum(1 for count in block_counter.values() if count > 1)
        
        print(f"  总块数: {len(blocks)}")
        print(f"  唯一块: {len(block_counter)}")
        print(f"  重复块: {repeated}")
        
        if repeated > 0:
            print(f"  最常见的块:")
            for block, count in block_counter.most_common(3):
                if count > 1:
                    hex_block = block.hex()
                    print(f"    {hex_block}: {count}次")

def try_stream_cipher_analysis(data):
    """流密码分析"""
    print("\n\n🌊 === 流密码分析 ===")
    
    # 检查是否可能是流密码（如RC4）
    # 流密码的特征：没有明显的块结构，字节分布相对均匀
    
    # 1. 检查与已知明文的XOR
    known_plaintexts = [
        b'"questionText"',
        b'"conversationId"',
        b'"userId"',
        b'"model"',
        b'{"question"',
        b'"sessionId"'
    ]
    
    for plaintext in known_plaintexts:
        print(f"\n尝试已知明文: {plaintext}")
        
        # 在数据中的不同位置尝试
        for offset in [0, 10, 20, 50, 100]:
            if offset + len(plaintext) > len(data):
                continue
            
            segment = data[offset:offset+len(plaintext)]
            key_stream = bytes(a ^ b for a, b in zip(segment, plaintext))
            
            # 检查密钥流是否有模式
            if len(set(key_stream)) < len(key_stream) * 0.8:  # 不够随机
                print(f"  偏移{offset}: 密钥流 {key_stream.hex()}")
                
                # 尝试用这个密钥流解密更多数据
                test_len = min(100, len(data) - offset)
                test_decrypt = bytes(data[offset+i] ^ key_stream[i % len(key_stream)] 
                                   for i in range(test_len))
                
                # 检查解密结果
                printable = sum(1 for b in test_decrypt if 32 <= b <= 126)
                if printable > test_len * 0.7:
                    print(f"    可能的解密: {test_decrypt[:50]}")

def analyze_as_encrypted_json(data):
    """作为加密的JSON分析"""
    print("\n\n🎯 === JSON结构分析 ===")
    
    # JSON的结构特征
    # 1. 通常以 { 开始，以 } 结束
    # 2. 包含成对的引号
    # 3. 有冒号和逗号分隔
    
    # 查找可能的JSON开始和结束
    print("查找可能的JSON边界:")
    
    # 假设第一个字节是 {
    possible_open_brace = data[0]
    print(f"假设 0x{possible_open_brace:02x} = '{{' (开始大括号)")
    
    # 假设最后一个字节是 }
    possible_close_brace = data[-1]
    print(f"假设 0x{possible_close_brace:02x} = '}}' (结束大括号)")
    
    # 基于这个假设创建初步映射
    initial_mapping = {
        possible_open_brace: ord('{'),
        possible_close_brace: ord('}')
    }
    
    # 查找可能的引号（应该是最频繁的）
    byte_freq = Counter(data)
    most_frequent = byte_freq.most_common(1)[0][0]
    print(f"\n假设 0x{most_frequent:02x} (最频繁) = '\"' (引号)")
    initial_mapping[most_frequent] = ord('"')
    
    # 应用初步映射看看效果
    test_decrypt = bytearray()
    for i in range(min(200, len(data))):
        byte = data[i]
        if byte in initial_mapping:
            test_decrypt.append(initial_mapping[byte])
        else:
            test_decrypt.append(byte)
    
    print(f"\n初步映射结果: {bytes(test_decrypt[:100])}")
    
    # 尝试找出更多映射
    find_more_mappings(data, initial_mapping)

def find_more_mappings(data, initial_mapping):
    """基于已知映射找出更多映射"""
    print("\n寻找更多字符映射:")
    
    # 如果是JSON，引号后面经常跟着特定模式
    quote_byte = [k for k, v in initial_mapping.items() if v == ord('"')][0]
    
    # 查找引号后面的字节
    after_quote = []
    for i in range(len(data)-1):
        if data[i] == quote_byte:
            after_quote.append(data[i+1])
    
    after_quote_freq = Counter(after_quote)
    print(f"\n引号后面最常见的字节:")
    for byte, count in after_quote_freq.most_common(5):
        print(f"  0x{byte:02x}: {count}次")
    
    # JSON中 ": 是常见模式
    # 查找可能的冒号
    for byte, count in after_quote_freq.most_common(3):
        if byte not in initial_mapping and count > 10:
            print(f"\n假设 0x{byte:02x} 可能是 ':' (冒号)")
            
            # 检查这个假设
            # 冒号后面通常是空格或引号
            after_colon = []
            for i in range(len(data)-1):
                if data[i] == byte:
                    after_colon.append(data[i+1])
            
            after_colon_freq = Counter(after_colon)
            print(f"  该字节后面最常见的:")
            for next_byte, next_count in after_colon_freq.most_common(3):
                print(f"    0x{next_byte:02x}: {next_count}次")

def try_substitution_cipher(data):
    """尝试替换密码解密"""
    print("\n\n🔤 === 替换密码分析 ===")
    
    # 基于字符频率创建映射
    # JSON中的预期字符频率（从高到低）
    json_freq_order = '",:{}[]entariosuqly0123456789'
    
    # 获取数据中的字符频率
    byte_freq = Counter(data)
    data_freq_order = [byte for byte, _ in byte_freq.most_common(len(json_freq_order))]
    
    # 创建映射
    mapping = {}
    for i, data_byte in enumerate(data_freq_order):
        if i < len(json_freq_order):
            mapping[data_byte] = ord(json_freq_order[i])
    
    # 解密
    decrypted = bytearray()
    for byte in data[:500]:  # 只测试前500字节
        decrypted.append(mapping.get(byte, byte))
    
    print(f"频率映射解密结果: {bytes(decrypted[:100])}")
    
    # 检查是否有改善
    printable = sum(1 for b in decrypted if 32 <= b <= 126)
    print(f"可打印字符比例: {printable/len(decrypted)*100:.1f}%")

def analyze_encryption_layers():
    """分析可能的加密层次"""
    print("\n\n🏗️ === 加密层次分析 ===")
    
    encrypted, decoded = load_data()
    
    print(f"原始加密数据: {len(encrypted)} 字符")
    print(f"Base64解码后: {len(decoded)} 字节")
    print(f"压缩比: {len(decoded)/len(encrypted):.2f}")
    
    # 可能的加密流程
    print("\n可能的加密流程:")
    print("1. 原始JSON")
    print("2. 第一层加密 (可能是字节替换或XOR)")
    print("3. 可能的压缩 (但熵值表明可能性不大)")
    print("4. 自定义Base64编码")
    print("5. 最终的加密字符串")
    
    # 尝试识别第二层加密
    print("\n第二层加密特征:")
    
    # 检查是否是简单的凯撒密码变体
    shifts = []
    for i in range(1, min(100, len(decoded))):
        shift = (decoded[i] - decoded[i-1]) % 256
        shifts.append(shift)
    
    shift_freq = Counter(shifts)
    if shift_freq.most_common(1)[0][1] > len(shifts) * 0.3:
        common_shift = shift_freq.most_common(1)[0][0]
        print(f"  可能存在固定位移: {common_shift}")
    
    # 检查是否有密钥扩展的迹象
    for key_len in [16, 32, 64, 128, 256]:
        pattern_found = True
        for i in range(min(10, len(decoded) // key_len)):
            if decoded[i] != decoded[i + key_len]:
                pattern_found = False
                break
        
        if pattern_found:
            print(f"  发现{key_len}字节的重复模式")

if __name__ == "__main__":
    encrypted, decoded = load_data()
    
    print("🔍 === 深入二进制分析 ===\n")
    
    byte_counts = analyze_byte_patterns(decoded)
    analyze_block_structure(decoded)
    try_stream_cipher_analysis(decoded)
    analyze_as_encrypted_json(decoded)
    try_substitution_cipher(decoded)
    analyze_encryption_layers()
    
    print("\n\n💡 === 分析总结 ===")
    print("基于深入分析：")
    print("1. 数据熵值较高，表明使用了较强的加密")
    print("2. 没有明显的块结构，可能不是块密码")
    print("3. 可能的加密方式：")
    print("   - 字节级别的替换密码")
    print("   - 流密码（如RC4）")
    print("   - 或自定义的加密算法")
    print("\n建议：")
    print("1. 需要通过动态调试获取运行时的加密密钥和算法")
    print("2. 或者需要更多的加密样本来找出规律")
    print("3. 可能需要反编译Go二进制文件中的加密函数")